from flask import Blueprint, jsonify, request, json, g
from sqlalchemy.orm import load_only
from exts import db
import datetime

from models import Users, Orders, Goods, Categories, Slides, Order_details
import decorators

bp = Blueprint("manager", __name__, url_prefix="/manager")


@decorators.login_reqiured
@bp.route("/getBoardInfo")
def getBoardInfo():
    user_count = Users.query.count()
    order_count = Orders.query.count()
    good_count = Goods.query.count()
    return jsonify({'user_count': user_count, 'order_count': order_count, 'good_count': good_count})


@decorators.login_reqiured
@bp.route("/getUserInfo")
def getUserInfo():
    i = db.session.query(Users.id, Users.name, Users.email, Users.avatar, Users.is_locked, Users.created_at).all()
    data = []
    for j in i:
        data.append({"key": j.id, "name": j.name, "email": j.email, "avatar": j.avatar, "is_locked": j.is_locked,
                     "created_at": j.created_at})
    return jsonify({'data': data})


@bp.route("/banUser")
def banUser():
    id = int(request.args.get('id'))
    if request.args.get('isBan') == 'true':
        isBan = True
    else:
        isBan = False
    try:
        i = Users.query.get(id)
        i.is_locked = isBan
        db.session.commit()
        return jsonify({'message': '操作成功', 'code': 3001})
    except:
        return jsonify({'message': '操作失败'})


@bp.route("/addUser", methods=['POST'])
def addUser():
    data = json.loads(request.data)
    name, email, password = data.get('name'), data.get('email'), data.get('password')
    try:
        user = Users(name=name, email=email, password=password, created_at=datetime.datetime.now())
        db.session.add(user)
        db.session.commit()
        return jsonify({'message': '已添加用户'})
    except:
        return jsonify({'message': '未知错误', 'code': 9999})


@bp.route("/deleteUser")
def deleteUser():
    id = request.args.get('id')
    try:
        i = Users.query.get(id)
        db.session.delete(i)
        db.session.commit()
        return jsonify({'message': '删除成功'})
    except:
        return jsonify({'message': '未知错误', 'code': 9999})


@bp.route("/editUser", methods=["POST"])
def editUser():
    data = json.loads(request.data)
    id, name, email, password = data.get('id'), data.get('name'), data.get('email'), data.get('password')
    try:
        i = Users.query.get(id)
        i.name = name
        i.email = email
        i.password = password
        db.session.commit()
        return jsonify({'message': '修改成功'})
    except:
        return jsonify({"message": "未知错误", 'code': 9999})


@decorators.login_reqiured
@bp.route("/getGoodInfo")
def getGoodInfo():
    i = db.session.query(Goods.id, Goods.pics, Goods.price, Goods.is_on, Goods.is_recommend, Goods.sales, Goods.title,
                         Goods.description, Goods.details, Goods.created_at, Goods.stock, Goods.category_id).all()
    data = []
    for j in i:
        data.append(
            {"key": j.id, "category": j.category_id, "title": j.title, "pics": j.pics, "price": j.price,
             "stock": j.stock, "sales": j.sales, "description": j.description, "details": j.details,
             "is_on": j.is_on, "is_recommend": j.is_recommend, "created_at": j.created_at})
    return jsonify({'data': data})


@bp.route("/onGood")
def onGood():
    id = int(request.args.get('id'))
    if request.args.get('is_on') == 'true':
        is_on = True
    else:
        is_on = False
    print(id, is_on)
    try:
        i = Goods.query.get(id)
        i.is_on = is_on
        db.session.commit()
        return jsonify({'message': '操作成功', 'code': 3002})
    except:
        return jsonify({'message': '操作失败'})


@bp.route("/recommendGood")
def recommendGood():
    id = int(request.args.get('id'))
    if request.args.get('is_recommend') == 'true':
        is_recommend = True
    else:
        is_recommend = False
    try:
        i = Goods.query.get(id)
        i.is_recommend = is_recommend
        db.session.commit()
        return jsonify({'message': '操作成功', 'code': 3003})
    except:
        return jsonify({'message': '操作失败'})


@bp.route("/addGood")
def addGood():
    title, price, stock, description, details, category = request.args.get('title'), request.args.get(
        'price'), request.args.get(
        'stock'), request.args.get('description'), request.args.get('details'), request.args.get('category')
    try:
        good = Goods(user_id=g.user_id, title=title, price=price, stock=stock, description=description, details=details,
                     category_id=category, created_at=datetime.datetime.now())
        db.session.add(good)
        db.session.commit()
        return jsonify({'message': '已添加商品'})
    except:
        return jsonify({'message': '未知错误', 'code': 9999})


@bp.route("/editGood")
def editGood():
    id, title, category, price, stock, description, details = request.args.get('id'), request.args.get(
        'title'), request.args.get('category'), request.args.get('price'), request.args.get('stock'), request.args.get(
        'description'), request.args.get('details')
    try:
        i = Goods.query.get(id)
        i.title = title
        i.category_id = category
        i.price = price
        i.stock = stock
        i.description = description
        i.details = details
        db.session.commit()
        return jsonify({'message': '修改成功'})
    except:
        return jsonify({"message": "未知错误", 'code': 9999})


@bp.route("/deleteGood")
def deleteGood():
    id = request.args.get('id')
    try:
        i = Goods.query.get(id)
        db.session.delete(i)
        db.session.commit()
        return jsonify({'message': '删除成功'})
    except:
        return jsonify({'message': '未知错误', 'code': 9999})


@bp.route("/getCategoryList")
def getCategoryList():
    i = db.session.query(Categories.id, Categories.name, Categories.pid).all()
    t = []
    i.sort(key=lambda category: category['pid'])

    def createObject(array, obj):
        for j in array:
            if j['key'] == obj.pid:
                j['children'].append({"key": obj.id, "title": obj.name, "children": []})
                return False
            if createObject(j['children'], obj) != False and createObject(j['children'], obj) is not None:
                array.append({"key": obj.id, "title": obj.name, "children": []})

    # for j in i:
    #     t.append({"value": j.id, "label": j.name})
    for y in i:
        if y.pid == 0:
            t.append({'key': y.id, "title": y.name, "children": []})
        else:
            createObject(t, y)
    return jsonify({'data': t})


@bp.route("/getCategoryRawList")
def getCategoryRawList():
    a = db.session.query(Categories.id, Categories.name).all()
    t = [{'value': 0, 'label': '新分类'}]
    for j in a:
        t.append({'value': j.id, 'label': j.name})
    return jsonify({'data': t})


@bp.route("/addCategory")
def addCategory():
    name, pid = request.args.get('name'), int(request.args.get('pid'))
    i = Categories(name=name, pid=pid, created_at=datetime.datetime.now())
    db.session.add(i)
    db.session.commit()
    return jsonify({'message': '添加成功'})


@bp.route("/deleteCategory")
def deleteCategory():
    id = int(request.args.get('id'))
    i = Categories.query.get(id)
    db.session.delete(i)
    db.session.commit()
    return jsonify({'message': '添加成功'})


@bp.route("/getSlideList")
def getSlideList():
    i = db.session.query(Slides.id, Slides.title, Slides.created_at, Slides.img, Slides.seq, Slides.status,
                         Slides.url).all()
    t = []
    for j in i:
        t.append({'key': j.id, 'title': j.title, 'img': j.img, 'seq': j.seq, 'status': j.status, 'url': j.url,
                  'created_at': j.created_at})
    return jsonify({'data': t})


@bp.route("/addSlide")
def addSlide():
    title, url, seq = request.args.get('title'), request.args.get('url'), request.args.get('seq')
    try:
        i = Slides(title=title, url=url, seq=seq, created_at=datetime.datetime.now(), img="jkljkl")
        db.session.add(i)
        db.session.commit()
        return jsonify({'message': '添加成功'})
    except:
        return jsonify({'message': '添加失败'})


@bp.route("/editSlide")
def editSlide():
    id, title, url, seq = request.args.get('id'), request.args.get('title'), request.args.get('url'), request.args.get(
        'seq')
    try:
        i = Slides.query.get(id)
        i.title = title
        i.url = url
        i.seq = seq
        db.session.commit()
        return jsonify({'message': '修改成功'})
    except:
        return jsonify({'message': '修改失败'})


@bp.route("/banSlide")
def banSlide():
    id = request.args.get("id")
    status = request.args.get("status") == 'true'
    i = Slides.query.get(id)
    i.status = status
    db.session.commit()
    return jsonify({'message': '禁用/启用成功'})


@bp.route("/deleteSlide")
def deleteSlide():
    id = request.args.get("id")
    i = Slides.query.get(id)
    db.session.delete(i)
    db.session.commit()
    return jsonify({'message': '删除成功'})


@bp.route("/getOrderList")
def getOrderList():
    i = Orders.query.all()
    t = []
    for j in i:
        t.append({'key': j.id, 'user': j.user.name, 'order_num': j.order_num, 'amount': j.amount, 'status': j.status,
                  'pay_time': j.pay_time, 'pay_type': j.pay_type, 'trade_num': j.trade_num})
    return jsonify({'data': t})


@bp.route("/getOrderDetails")
def getOrderDetails():
    id = request.args.get("id")
    i = Orders.query.get(id)
    t = []
    for j in i.order_details:
        t.append({'key': j.id, 'title': j.good.title, 'price': j.price, 'num': j.num})
    return jsonify({'data': t})


@bp.route("/setExpress")
def setExpress():
    id, expressType, expressNum = request.args.get("id"), request.args.get("expressType"), request.args.get(
        "expressNum")
    try:
        i = Orders.query.get(id)
        if i.status != 2:
            return jsonify({'message': '未知错误', 'code': 9999})
        i.express_type = expressType
        i.express_num = expressNum
        i.status = 3
        db.session.commit()
        return jsonify({'message': '发货成功'})
    except:
        return jsonify({'message': '未知错误', 'code': 9999})
